//
//  COCOnversationViewCell.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import UIKit

class COCOnversationViewCell: RCConversationBaseCell {
    
    static let reusedID = "COCOnversationViewCell"
    public func cellWithTableView(_ tableView:UITableView) -> COCOnversationViewCell{
        var cell:COCOnversationViewCell! = tableView.dequeueReusableCell(withIdentifier: COCOnversationViewCell.reusedID) as? COCOnversationViewCell
        if cell == nil {
            cell = (Bundle.main.loadNibNamed("COCOnversationViewCell", owner: nil, options: nil)?.first as! COCOnversationViewCell)
        }
        return cell!
    }
    
    // 容器
    @IBOutlet weak var containBg: UIView!
    // 头像
    @IBOutlet weak var iconImg: UIImageView!
    // 昵称
    @IBOutlet weak var nameLbl: UILabel!
    // 昵称右间距
    @IBOutlet weak var nameRightCon: NSLayoutConstraint!
    // 文本
    @IBOutlet weak var contentLbl: UILabel!
    // 时间
    @IBOutlet weak var timeLbl: UILabel!
    // 未读数量
    @IBOutlet weak var countLbl: UILabel!
    // 数量宽度
    @IBOutlet weak var countWidthCon: NSLayoutConstraint!
    // 视频按钮
    @IBOutlet weak var VideoBtb: UIButton!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.containBg.layer.cornerRadius = PTW(20)
        self.containBg.layer.masksToBounds = true
        
        self.iconImg.contentMode = .scaleAspectFill
        self.iconImg.layer.cornerRadius = 40
        self.iconImg.layer.masksToBounds = true
        
        self.countLbl.layer.cornerRadius = 9
        self.countLbl.layer.masksToBounds = true
        
        // 头像点击
        self.iconImg.addTap {[weak self] ges in
            guard self?.model.targetId.range(of: "_") != nil else {
                return
            }
            if self?.model.conversationType == RCConversationType.ConversationType_SYSTEM{
                return
            }
            let components = self?.model.targetId.components(separatedBy: "_")
            if let lastComponent = components?.last {
                let profile = COOtherInfoController()
                profile.userId = lastComponent
                self?.viewController()?.navigationController?.pushViewController(profile, animated: true)
            }
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }
    
    override func setDataModel(_ model: RCConversationModel!) {
        self.model = model
        if let messageContent = model!.lastestMessage {
            if messageContent.isMember(of: RCTextMessage.self) {
                let textMsg = messageContent as! RCTextMessage
                self.contentLbl.text = textMsg.content
            }else if messageContent.isMember(of: RCImageMessage.self) {
                self.contentLbl.text = "[Photo]"
            }else {
                self.contentLbl.text = messageContent.conversationDigest()
            }
        }
        if model!.conversationType == RCConversationType.ConversationType_SYSTEM{
            iconImg.image = KImaged("coco_msg_system")
            self.nameLbl.text = "System"
            self.VideoBtb.isHidden = true
            self.nameRightCon.constant = 18
        }else {
            self.VideoBtb.isHidden = false
            self.nameRightCon.constant = 70
            RCIM.shared().userInfoDataSource.getUserInfo(withUserId: model!.targetId, completion: { (userInfo) in
                if let user = userInfo {
                    self.iconImg.sd_setUrlImage(user.portraitUri, placeholder: KImaged("coco_icon_holder"))
                    if let dictionary = stringToDictionary(jsonString: user.name) {
                        self.nameLbl.text = dictionary["name"] as? String
                    }else{
                        self.nameLbl.text = user.name
                    }
                }
            })
            
            let status = model.extend as? Int
            if (status == 1){
                self.VideoBtb.setImage(KImaged("coco_video_online"), for: .normal)
            }else if (status == 2){
                self.VideoBtb.setImage(KImaged("coco_video_busy"), for: .normal)
            }else{
                self.VideoBtb.setImage(KImaged("coco_video_offline"), for: .normal)
            }
        }
        
        if (model?.unreadMessageCount ?? 0 > 0){
            self.countLbl.isHidden = false
            var count = "\(model?.unreadMessageCount ?? 0)"
            if (model!.unreadMessageCount > 99){
                count = "99+"
            }
            let size = count.size(width:  CGFloat(MAXFLOAT), font:UIFont.systemFont(ofSize: 12))
            self.countLbl.text = count
            if (size.width > 18){
                self.countWidthCon.constant = size.width + 5
            }else{
                self.countWidthCon.constant = 20
            }
        }else{
            self.countLbl.isHidden = true
        }
    
        var sentOrReceivedTime: Int64 = 0
        if model!.lastestMessageDirection == .MessageDirection_RECEIVE {
            sentOrReceivedTime = model!.receivedTime
        }else {
            sentOrReceivedTime = model!.sentTime
        }
        let now = Date().timeIntervalSince1970
        let delta = Int64(now) - sentOrReceivedTime / 1000
        let minutes = delta / 60;
        let hours = delta / 60 / 60;
        let days = delta / 60 / 60 / 24;
        let months = delta / 60 / 60 / 24 / 30;
        let years = delta / 60 / 60 / 24 / 365;
        var sendOrReceiveStr = ""
        if minutes <= 1 {
            sendOrReceiveStr = "Just"
        } else if minutes < 60 {
            sendOrReceiveStr =  "\(minutes) minutes ago"
        } else if (hours < 24) {
            sendOrReceiveStr =  "\(hours) hours ago"
        } else if (days < 30) {
            sendOrReceiveStr =  "\(days) days ago"
        } else if (months < 12) {
            sendOrReceiveStr = Date(timeIntervalSince1970: Double(sentOrReceivedTime)).toString("MM-dd")
        } else if (years >= 1) {
            sendOrReceiveStr = Date(timeIntervalSince1970: Double(sentOrReceivedTime)).toString("yyyy-MM-dd")
        }
        self.timeLbl.text = sendOrReceiveStr
    
    }
    
    @IBAction func videoAction(_ sender: UIButton) {
        guard self.model.targetId.range(of: "_") != nil else {
            return
        }
        let components = self.model.targetId.components(separatedBy: "_")
        if let lastComponent = components.last {
            print(lastComponent) // 输出
            self.viewController()?.requestStatus(userId: String(lastComponent))
        }
    }
    
}
